package com.hotel.project.demo.controller;


import com.github.pagehelper.PageInfo;
import com.hotel.project.demo.domain.BaseEntity;
import com.hotel.project.demo.domain.ResponseBean;
import com.hotel.project.demo.service.base.ICurdService;
import com.hotel.project.demo.utils.GenericUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

public abstract class BaseController<S extends ICurdService<T>, T extends BaseEntity> {
    @Autowired
    protected S service;

    protected Logger LOG = LoggerFactory.getLogger(this.getClass());

    protected Class<T> entityClass;

    public BaseController(){
        this.entityClass = GenericUtil.getSuperGenericClass2(this.getClass());
    }

    /**
     * 根据id获取信息
     * @param id
     * @return
     */
    @GetMapping("/select-by-id")
    public ResponseBean selectById(@PathVariable Long id){
        ResponseBean responseBean = new ResponseBean();
        T entity = service.getById(id);
        if (entity != null){
            responseBean.setData(entity);
        }else {
            responseBean = errorEdit(responseBean,300l);
        }
        return responseBean;
    }

    /**
     * 分页查询
     * @param entity
     * @param page
     * @param rows
     * @return
     */
    @PostMapping("/list-page")
    public PageInfo<T> listpage(T entity, @RequestParam(name = "page",defaultValue = "1",required = false)int page,
                                @RequestParam(name = "rows",defaultValue = "10",required = false)int rows){
        PageInfo<T> result = service.listPage(entity,page,rows);
        return result;
    }

    /**
     * 根据实体条件查询
     * @param entity
     * @return
     */
    @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST})
    public ResponseBean list(T entity){
        ResponseBean responseBean = new ResponseBean();
        List<T> list = service.list(entity);
        responseBean.setData(list);
        return responseBean;
    }

    /**
     * 保存前执行
     * @param entity
     * @throws Exception
     */
    public void beforeSave(T entity) throws Exception {
    }
    /**
     * 模板方法：在加载后执行
     * @param entity
     */
    public void afterEdit(T entity) {
    }

    public ResponseBean errorEdit(ResponseBean responseBean,Long code){
        responseBean.setCode(code);
        responseBean.setMessage("fail");
        return responseBean;
    }
}
